package com.sugar.subscribe.course.module.business.controller.admin.order;

import com.sugar.subscribe.course.module.pay.api.notify.dto.PayOrderNotifyReqDTO;
import com.sugar.subscribe.course.module.pay.api.notify.dto.PayRefundNotifyReqDTO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.annotation.security.PermitAll;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import com.sugar.subscribe.course.framework.common.pojo.PageParam;
import com.sugar.subscribe.course.framework.common.pojo.PageResult;
import com.sugar.subscribe.course.framework.common.pojo.CommonResult;
import static com.sugar.subscribe.course.framework.common.pojo.CommonResult.success;

import com.sugar.subscribe.course.framework.excel.core.util.ExcelUtils;

import com.sugar.subscribe.course.framework.apilog.core.annotation.ApiAccessLog;
import static com.sugar.subscribe.course.framework.apilog.core.enums.OperateTypeEnum.*;

import com.sugar.subscribe.course.module.business.controller.admin.order.vo.*;
import com.sugar.subscribe.course.module.business.service.order.OrderService;

@Tag(name = "管理后台 - 订单")
@RestController
@RequestMapping("/business/order")
@Validated
public class OrderController {

    @Resource
    private OrderService orderService;

    @PutMapping("/update")
    @Operation(summary = "更新订单")
    @PreAuthorize("@ss.hasPermission('business:order:update')")
    public CommonResult<Boolean> updateOrder(@Valid @RequestBody OrderSaveReqVO updateReqVO) {
        orderService.updateOrder(updateReqVO);
        return success(true);
    }

    @PutMapping("/update/amount")
    @Operation(summary = "修改订单金额")
    @PreAuthorize("@ss.hasPermission('business:order:update')")
    public CommonResult<Boolean> updateOrderAmount(@Valid @RequestBody OrderAmountUpdateReqVO amountUpdateReqVO) {
        orderService.updateOrderAmount(amountUpdateReqVO);
        return success(true);
    }

    @PutMapping("/update/attend-class")
    @Operation(summary = "后台操作上课")
    @PreAuthorize("@ss.hasPermission('business:order:update')")
    public CommonResult<Boolean> orderAttendClass(@Valid @RequestBody OrderAttendClassReqVO amountUpdateReqVO) {
        orderService.orderAttendClass(amountUpdateReqVO);
        return success(true);
    }

    @PutMapping("/update/cancel/{id}")
    @Operation(summary = "后台取消订单")
    @PreAuthorize("@ss.hasPermission('business:order:update')")
    public CommonResult<Boolean> backOrderCancel(@PathVariable("id") Long id) {
        orderService.backOrderCancel(id);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除订单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('business:order:delete')")
    public CommonResult<Boolean> deleteOrder(@RequestParam("id") Long id) {
        orderService.deleteOrder(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除订单")
                @PreAuthorize("@ss.hasPermission('business:order:delete')")
    public CommonResult<Boolean> deleteOrderList(@RequestParam("ids") List<Long> ids) {
        orderService.deleteOrderListByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得订单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('business:order:query')")
    public CommonResult<OrderDetailRespVO> getOrder(@RequestParam("id") Long id) {
        return success(orderService.getOrder(id));
    }

    @GetMapping("/page")
    @Operation(summary = "获得订单分页")
    @PreAuthorize("@ss.hasPermission('business:order:query')")
    public CommonResult<PageResult<OrderRespVO>> getOrderPage(@Valid OrderPageReqVO pageReqVO) {
        return success(orderService.getOrderPage(pageReqVO));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出订单 Excel")
    @PreAuthorize("@ss.hasPermission('business:order:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportOrderExcel(@Valid OrderPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        // 导出 Excel
        ExcelUtils.write(response, "订单.xls", "数据", OrderRespVO.class,
                orderService.getOrderPage(pageReqVO).getList());
    }


    @PostMapping("/update-paid")
    @Operation(summary = "更新订单为已支付") // 由 pay-module 支付服务，进行回调，可见 PayNotifyJob
    @PermitAll // 无需登录，安全由 BusinessOrderService 内部校验实现
    public CommonResult<Boolean> updateOrderPaid(@RequestBody PayOrderNotifyReqDTO notifyReqDTO) {
        orderService.updateOrderPaid(notifyReqDTO.getMerchantOrderId(),
                notifyReqDTO.getPayOrderId());
        return success(true);
    }

    @PostMapping("/update-refunded")
    @Operation(summary = "更新订单为已退款") // 由 pay-module 支付服务，进行回调，可见 PayNotifyJob
    @PermitAll // 无需登录，安全由 BusinessOrderService 内部校验实现
    public CommonResult<Boolean> updateOrderRefunded(@RequestBody PayRefundNotifyReqDTO notifyReqDTO) {
        orderService.updateOrderRefunded(notifyReqDTO.getMerchantRefundId(),
                notifyReqDTO.getPayRefundId());
        return success(true);
    }
}